import { Directive, Input, TemplateRef, ViewContainerRef, OnInit, NgZone, OnChanges, SimpleChanges, ViewRef, EmbeddedViewRef } from '@angular/core';
import { DxDataGridComponent } from 'devextreme-angular/ui/data-grid';

@Directive({
  selector: '[bzSummary]'
})
export class SummaryDirective implements OnInit, OnChanges {

  @Input() bzSummary: TemplateRef<null> | string;
  @Input() bzSummaryContext: any;

  private hostEle: HTMLDivElement;
  private viewRef: EmbeddedViewRef<TemplateRef<null>>;
  private setupSummaryTimeoutId: any;

  constructor(
    private dxDataGridComponent: DxDataGridComponent,
    private viewContainerRef: ViewContainerRef,
    private ngZone: NgZone
  ) { }

  ngOnChanges(changes: SimpleChanges): void {
    if (this.hostEle && (changes.bzSummary || changes.bzSummaryContext)) {
      this.setupSummary();
    }
  }

  ngOnInit(): void {
    this.ngZone.runOutsideAngular(() => {
      setTimeout(() => {
        this.hostEle = this._initEle();
        this.setupSummary();
      }, 300);
    });
  }

  private setupSummary() {
    clearTimeout(this.setupSummaryTimeoutId);

    this.ngZone.runOutsideAngular(() => {
      this.setupSummaryTimeoutId = setTimeout(() => {
        if (typeof this.bzSummary === 'string') {
          this.hostEle.innerHTML = this.bzSummary;
        } else {
          if (this.viewRef) {
            this.viewRef.rootNodes.forEach(rootNode => this.hostEle.removeChild(rootNode));
            this.viewRef.destroy();
          }
          this.viewRef = this.viewContainerRef.createEmbeddedView(<TemplateRef<null>>this.bzSummary, this.bzSummaryContext);
          this.viewRef.rootNodes.forEach(rootNode => this.hostEle.appendChild(rootNode));
          this.viewRef.detectChanges();
        }
      }, 0);
    });
  }

  private _initEle() {
    const hostEle = document.createElement('div');
    const dataGridEle = this.dxDataGridComponent.instance.element();
    const dataGridContainerEle = dataGridEle.querySelector('.dx-datagrid');
    const dataGridHeadersEle = dataGridContainerEle.querySelector('.dx-datagrid-headers');
    const rowsviewEle = dataGridContainerEle.querySelector('.dx-datagrid-rowsview');
    hostEle.style.cssText = `
      border-style: solid;
      border-color: ${window.getComputedStyle(dataGridHeadersEle).getPropertyValue('border-bottom-color')};
      border-width: 1px;
      padding: 10px;
      text-align: right;
      margin-top: -1px;
    `;
    rowsviewEle.insertAdjacentElement('afterend', hostEle);
    return hostEle;
  }
}
